<?php

namespace Yolo\Captcha\Core\Engines;

use Yolo\Captcha\Core\CaptchaResult;
use Yolo\Captcha\Core\Helper;

/**
 * 普通字符串类
 */
class Character implements CaptchaInterface
{
    private string $characters = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';

    public function create(array $config): CaptchaResult
    {
        $characters = $this->createRandomCharacter($config['length']);

        $text = implode('', array_map(function ($character) {

            return $character['text'];
        }, $characters));
        return new CaptchaResult([
            'text' => $text,
            'answer' => $text,
            'textData' => $characters,
        ]);
    }

    private function createRandomCharacter(int $length): array
    {
        $characterLength = mb_strlen($this->characters);

        $characters = [];
        for ($i = 0; $i < $length; $i++) {
            $characters[] = [
                'text' => mb_substr($this->characters, mt_rand(0, $characterLength - 1), 1),
                'color' => Helper::getRandomFontColor(),
                'spacing' => 35,
                'angle' => Helper::getRandomAngle(),
            ];
        }

        return $characters;
    }

}
